package com.sczmgk.hotline.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.view.WindowManager;

import com.sczmgk.hotline.MyApp;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.dialog.DialogFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PictureUtil {
	/**
	 * 头像图片最大宽度
	 */
	public static int IMAGE_SIZE_HEAD_MAX_WIDTH = -1;
	/**
	 * 头像图片最大高度
	 */
	public static int IMAGE_SIZE_HEAD_MAX_HEIGHT = -1;
	/**
	 * 聊天图片最大宽度
	 */
	public static int IMAGE_SIZE_CHAT_MAX_WIDTH = -1;
	/**
	 * 聊天图片最大高度
	 */
	public static int IMAGE_SIZE_CHAT_MAX_HEIGHT = -1;
	/**
	 * 屏幕高度
	 */
	public static int DISPLAY_SCREEN_HEIGHT = -1;
	/**
	 * 屏幕宽度
	 */
	public static int DISPLAY_SCREEN_WIDTH = -1;
	private static String TAG = "PictureUtil";
	

	/**
	 * 初始化图片测量尺寸
	 * @param context
	 */
	public static void initImageMeasureSize(Context context) {
		int imageSizeDipHeadMaxWidth = 100;
		int imageSizeDipHeadMaxHeight = 100;
		IMAGE_SIZE_HEAD_MAX_WIDTH = Tools.dip2px(context,imageSizeDipHeadMaxWidth);
		IMAGE_SIZE_HEAD_MAX_HEIGHT = Tools.dip2px(context,imageSizeDipHeadMaxHeight);
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		IMAGE_SIZE_CHAT_MAX_HEIGHT = Tools.dip2px(context,imageSizeDipHeadMaxWidth);
		IMAGE_SIZE_CHAT_MAX_WIDTH = Tools.dip2px(context,imageSizeDipHeadMaxHeight);
		DISPLAY_SCREEN_HEIGHT = windowManager.getDefaultDisplay().getHeight();
		DISPLAY_SCREEN_WIDTH = windowManager.getDefaultDisplay().getWidth();
		
	}

	/**
	 * 把bitmap转换成Base64字符串
	 * 
	 * @param bm Bitmap
	 * @return  bast64字符串
	 */
	public static String bitmapToString(Bitmap bm) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
		byte[] b = baos.toByteArray();

		return Base64.encodeToString(b, Base64.DEFAULT);

	}

	/**
	 * 计算图片的缩放值
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return   图片的缩放值
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	/**
	 * 根据路径获得图片并压缩返回bitmap用于显示 480*800
	 * 
	 * @param filePath
	 * @return  480*800 的bitMap
	 */
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize 主流机型屏幕大小
		options.inSampleSize = calculateInSampleSize(options, 480, 800);

		//
		options.inPreferredConfig = Bitmap.Config.RGB_565; // 这里也可以是ARGB_8888
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 根据路径获得图片并压缩返回bitmap用于显示 100*100大小
	 * 
	 * @param filePath
	 * @return  返回100*100的图片
	 */
	public static Bitmap getBitmap(String filePath) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		int be = 1;
		try {
			FileInputStream fis = new FileInputStream(new File(filePath));
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(fis, null, options);
			float f = 100;
			if (options.outHeight > options.outWidth) {
				be = (int) (options.outHeight / f);
			} else {
				be = (int) (options.outWidth / f);
			}
			if (be <= 0)
				be = 1;
			options.inSampleSize = be;
			options.inPreferredConfig = Bitmap.Config.ARGB_8888;
			options.inJustDecodeBounds = false;
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 质量压缩方法(得到的bitmap如果再次存入文件.jpg格式 如不进行再次压缩  bm.compress(format,100,fos),将会得到一张不清晰，并且很大的图片)
	 * 
	 * @param image
	 * @return
	 */
	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 图片按比例大小压缩方法（根据路径获取图片并压缩）
	 * 
	 * @param srcPath
	 * @return   压缩后的图片 480*800
	 */
	public static Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		if (null == bitmap) {
			return null;
		}
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 图片按比例大小压缩方法（根据Bitmap图片压缩）
	 * 
	 * @param image
	 * @return    返回480*800的图片
	 */
	public static Bitmap comp(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 根据uri获取图片/视频绝对路径或者视频时长 只支持MediaStore.Images.Media.单个查询
	 * @param uri 
	 * @param str
	 * @param mActivity
	 * @return  返回图片的绝对路径或视频时长
	 */
    public static String getAbsoluteImageandVideoPath(Uri uri, String[] str, Activity mActivity) {
        if (null == str || str.length != 1) {
            return null;
        }
        // can post image
        Cursor cursor = null;
        try {
            cursor = mActivity.getContentResolver().query(uri, str, null, null, null);
            if (null == cursor) {
                return null;
            }
            int column_index = cursor.getColumnIndexOrThrow(str[0]);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    /**
     * 得到图片数据源之后 进行预压缩处理
     * @param uri
     * @param handler
     * @param activity
     * @param requestResultCode
     * @param isFromCamera
     */
	public static void startPhotoZoom(Uri uri, final Handler handler,
									  final Activity activity, final int requestResultCode, boolean isFromCamera) {
		startPhotoZoom(uri, handler, activity, null, requestResultCode, -1, -1, -1, -1,isFromCamera);
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * @param uri  图片的url 
	 * @param handler
	 * @param activity
	 * @param requestResultCode  请求结果码
	 * @param aspectX   方向 X
	 * @param aspectY   方向 Y 
	 * @param isFromCamera  是否来自相机
	 */
	public static void startPhotoZoomClipLimit(Uri uri, final Handler handler,
											   final Activity activity, final int requestResultCode, final int aspectX,
											   final int aspectY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, activity, null, requestResultCode, aspectX, aspectY, 250, 250,isFromCamera);
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * @param uri   图片的url
	 * @param handler
	 * @param activity
	 * @param requestResultCode   请求结果码
	 * @param outputX  输出X
	 * @param outputY  输出Y
	 * @param isFromCamera  是否来自相机
	 */
	public static void startPhotoZoomOutputLimit(Uri uri, final Handler handler,
												 final Activity activity, final int requestResultCode,
												 final int outputX, final int outputY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, activity, null, requestResultCode, -1, -1, outputX, outputY,isFromCamera);
		
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * @param uri  图片的url
	 * @param handler
	 * @param activity
	 * @param requestResultCode
	 * @param requestResultCode   请求结果码
	 * @param aspectX   方向 X
	 * @param aspectY   方向 Y 
	 * @param outputX  输出X
	 * @param outputY  输出Y
	 * @param isFromCamera  是否来自相机
	 */
	public static void startPhotoZoom(final Uri uri, final Handler handler,
									  final Activity activity, final int requestResultCode, final int aspectX,
									  final int aspectY, final int outputX, final int outputY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, activity, null, requestResultCode, aspectX, aspectY, outputX, outputY, isFromCamera);;
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param handler
	 * @param fragment
	 * @param requestResultCode
	 * @param isFromCamera
	 */
	public static void startPhotoZoom(Uri uri, final Handler handler,
									  final Fragment fragment, final int requestResultCode, boolean isFromCamera) {
		startPhotoZoom(uri, handler, null, fragment, requestResultCode, -1, -1, -1, -1,isFromCamera);
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param handler
	 * @param fragment
	 * @param requestResultCode
	 * @param aspectX
	 * @param aspectY
	 * @param isFromCamera
	 */
	public static void startPhotoZoomClipLimit(Uri uri, final Handler handler,
											   final Fragment fragment, final int requestResultCode, final int aspectX,
											   final int aspectY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, null, fragment, requestResultCode, aspectX, aspectY, -1, -1,isFromCamera);
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param handler
	 * @param fragment
	 * @param requestResultCode
	 * @param outputX
	 * @param outputY
	 * @param isFromCamera
	 */
	public static void startPhotoZoomOutputLimit(Uri uri, final Handler handler,
												 final Fragment fragment, final int requestResultCode,
												 final int outputX, final int outputY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, null, fragment, requestResultCode, 100, 100, outputX, outputY,isFromCamera);
		
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param handler
	 * @param fragment
	 * @param requestResultCode
	 * @param aspectX
	 * @param aspectY
	 * @param outputX
	 * @param outputY
	 * @param isFromCamera
	 */
	public static void startPhotoZoom(final Uri uri, final Handler handler,
									  final Fragment fragment, final int requestResultCode, final int aspectX,
									  final int aspectY, final int outputX, final int outputY, boolean isFromCamera) {
		startPhotoZoom(uri, handler, null, fragment, requestResultCode, aspectX, aspectY, outputX, outputY, isFromCamera);;
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param handler
	 * @param activity
	 * @param fragment  
	 * @param requestResultCode   请求结果码
	 * @param aspectX   方向 X
	 * @param aspectY   方向 Y 
	 * @param outputX  输出X
	 * @param outputY  输出Y
	 * @param isFromCamera  是否来自相机
	 */
	private static void startPhotoZoom(final Uri uri, final Handler handler,
									   final Activity activity, final Fragment fragment, final int requestResultCode, final int aspectX,
									   final int aspectY, final int outputX, final int outputY, boolean isFromCamera) {
		if(isFromCamera){
			Context context = null;
			if(activity!=null){
				context = activity;
			}else if(fragment!=null){
				context = fragment.getActivity();
			}
			String imagePath = uri.getPath();
			int angle = BitmapUtils.readPictureDegree(imagePath);
			if(angle>0){
				final Dialog loadingDialog = DialogFactory.getLoadingDialog(context, R.string.common_image_compress_doing);
				loadingDialog.show();
				BitmapUtils.compressBitmap(FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH, imagePath, 400, 400, new BitmapUtils.CompressBitmapCallback() {
							
						@Override
						public void compress(String imagePath) {
							
							handler.post(new Runnable() {
								
								@Override
								public void run() {
								}
							});
							if(imagePath!=null&&!Tools.isEmpty(imagePath)){
								startPhotoZoom(Uri.fromFile(new File(imagePath)), aspectX, aspectY, outputX, outputY, requestResultCode, activity,fragment);
										
							}else{
								handler.post(new Runnable() {
									
									@Override
									public void run() {
										DialogFactory.warningDialog(activity, R.string.clip_error);
									}
								});
							}
							loadingDialog.dismiss();
						}
				});
			}else{
				startPhotoZoom(uri, aspectX, aspectY, outputX, outputY, 
						 requestResultCode, activity,fragment);
			}
		}else{
			startPhotoZoom(uri, aspectX, aspectY, outputX, outputY,
					requestResultCode, activity,fragment);
		}
	}
	/**
	 * 得到图片数据源之后 进行预压缩处理
	 * 
	 * @param uri  图片的url
	 * @param aspectX
	 * @param aspectY
	 * @param outputX
	 * @param outputY
	 * @param requestResultCode
	 * @param activity
	 * @param fragment
	 */
	private static void startPhotoZoom(Uri uri, final int aspectX,
									   final int aspectY, final int outputX, final int outputY,
									   int requestResultCode, final Activity activity, final Fragment fragment){
		File clipeTempFloder = new File(FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH);
		if(!clipeTempFloder.isDirectory()){
			clipeTempFloder.mkdirs();
		}
		MyLog.i(TAG,"生成文件的路径是: "+getClipTempFile());
		File clipTempFile = new File(getClipTempFile());
		Intent intent = new Intent("com.android.camera.action.CROP");//系统的裁切图片
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		if(aspectX>0&&aspectY>0){
			intent.putExtra("aspectX", aspectX);
			intent.putExtra("aspectY", aspectY);
		}
		if(outputX>0&&outputY>0){
			intent.putExtra("outputX", outputX);
			intent.putExtra("outputY", outputY);
		}
		Uri outputFileUri = Uri.fromFile(clipTempFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri );
		MyLog.d(TAG,"裁剪图片的文件是： "+clipTempFile.toString()+"     剪裁图片的URL: "+outputFileUri.toString());
		if(activity!=null){
			activity.startActivityForResult(intent, requestResultCode);
		}else{
			fragment.startActivityForResult(intent, requestResultCode);
		}
		
		
	}

	/**
	 * 根据路径删除图片
	 * 
	 * @param path
	 */
	public static void deleteTempFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 添加到图库
	 * @param context
	 * @param path
	 */
	public static void galleryAddPic(Context context, String path) {
		Intent mediaScanIntent = new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(path);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		context.sendBroadcast(mediaScanIntent);
	}

	/**
	 * 获取保存图片的目录
	 * 
	 * @return
	 */
	public static File getAlbumDir() {
		File dir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				getAlbumName());
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}
	/**
	 * 获取剪切的临时文件名
	 * @return
	 */
	public static String getClipTempFile(){
		
		return FileUtil.getUserImageCacheDir(MyApp.loginUserName )+ File.separator+ "ClipTemp.jpg";
	}

	/**
	 * 获取保存 隐患检查的图片文件夹名称
	 * 
	 * @return
	 */
	public static String getAlbumName() {
		return "sheguantong";
	}



   public interface OnsavePicListener{
	   void onSuccess();
	   void onFailure(String msg);
   }

	public static void savePNG_After(Bitmap bitmap, File file, OnsavePicListener onsavePicListener) {




		if(file.exists()){
			MyLog.d(TAG,"文件存在");
		}else{
			MyLog.e(TAG,"文件不存在：");
		}
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
				if(onsavePicListener != null){
					onsavePicListener.onSuccess();
				}
			}
		} catch (FileNotFoundException e) {
			if(onsavePicListener != null){
				onsavePicListener.onFailure(e.toString());
			}
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			if(onsavePicListener != null){
				onsavePicListener.onFailure(e.toString());
			}
		}
	}
}
